import { Group } from '../models'
import { findGroupStudents } from './group'
import { download, stitchFixedTotalSizeCeil } from '../lib/images'
import CONFIG from '../config'
import kue from 'kue'
import COS from 'cos-nodejs-sdk-v5'

var queue = kue.createQueue({ redis: CONFIG.redis })

queue.process('group_avatar', async function(job, done) {
  done()
  let groupId = job.data.groupId
  if (!groupId) {
    console.error('Must specify Group ID')
  }
  let users = await findGroupStudents(groupId)
  let downloads = []

  // save user avatar into local for group avatar assembly
  for (let i = 0; i < users.length; i++) {
    downloads.push(
      download(users[i].avatarUrl, `./download/${users[i].openId}.jpg`)
    )
  }
  let avatars = await Promise.all(downloads)
  console.log(avatars)

  let result = await stitchFixedTotalSizeCeil(
    avatars,
    `./avatars/${groupId}.jpg`
  )
  console.log('uploading:' + result)
  // upload to qcloud
  // 创建实例
  var cos = new COS({
    SecretId: CONFIG.cos.SecretId,
    SecretKey: CONFIG.cos.SecretKey
  })
  // 分片上传
  cos.sliceUploadFile(
    {
      Bucket: CONFIG.cos.Bucket,
      Region: CONFIG.cos.Region,
      Key: `avatars/${groupId}.jpg`,
      FilePath: `./avatars/${groupId}.jpg`
    },
    async function(err, data) {
      if (!err) {
        let group = await Group.findById(groupId)
        if (group) {
          group.avatarUrl = 'https://' + data.Location
          group.save()
        }
      } else {
        console.log(err, data)
      }
    }
  )
})

/**
 * Add a group avatar generate task
 * @param {int} groupId
 */
export const generateAvatar = async groupId => {
  if (!groupId) {
    throw new Error('Must specify Group ID')
  }
  queue
    .create('group_avatar', {
      groupId
    })
    .save()
}
